package com.qingcheng.controller.file;

import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private HttpServletRequest request;

    //接受文件参数类型必须为 MultipartFile
    @PostMapping("/native")
    public String nativeUpload(@RequestParam("file") MultipartFile file) {
        //获取根目录下存储图片的绝对地址
        String path = request.getSession().getServletContext().getRealPath("img");
        //创建保存文件的文件夹
        String filePath = path + "/" + file.getOriginalFilename();
        File desFile = new File(filePath);
        if (!desFile.getParentFile().exists()) {
            desFile.mkdirs();
        }
        try {
            //将图片文件写入硬盘
            file.transferTo(desFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("path:---" + filePath);
        return "http://localhost:9101/img/" + file.getOriginalFilename();
    }

    @Autowired
    private OSSClient ossClient;

    /**
     * LTAIP4GONs27eqql
     * M9CigVMTkoHVSvDdn6mzO4oSOHdPC5
     * bucket名  project--qingcheng
     * 外网访问  oss-cn-beijing.aliyuncs.com
     *
     * @param file
     * @param folder
     * @return
     */
    @PostMapping("/oss")
    public String ossUpload(@RequestParam("file") MultipartFile file, String folder)  {
        String bucketName = "project--qingcheng";
        String fileName= folder+"/"+ UUID.randomUUID()+"_"+file.getOriginalFilename();
//        String fileName = "zhouya/" + UUID.randomUUID() + "_" + file.getOriginalFilename();
        try {
            //上传文件
            ossClient.putObject(bucketName, fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "https://"+bucketName+"."+ ossClient.getEndpoint().toString().replace("http(https)://","") +"/"+fileName;
//        return "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + fileName;
    }

}
